package com.ruubypay.web.core.generator.plugins;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Desc : FreeMarker 模版操作工具类
 * @author sucyun 
 * Date :2018/3/17 下午1:38
 */
public class FreeMarkerUtil {

	private static final String PROJECT_PATH = System.getProperty("user.dir");
	/**
	 * 获取模板
	 * @param name 模版名称
	 * @return 返回模版对象
	 */
	public Template getTemplate(String templatePath,String name) {
		try {
			templatePath = templatePath+"resources/template/";
			Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
			cfg.setDefaultEncoding("UTF-8");
			cfg.setDirectoryForTemplateLoading(new File(templatePath));
			return cfg.getTemplate(name);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 打印应用模板的结果到控制台
	 *
	 * @param name
	 * @param root
	 */
	public void print(String name, Map<String, Object> root) {
		try {
			Template template = this.getTemplate("",name);
			template.process(root, new PrintWriter(System.out));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void viewTemplatePrint(String domainObjectName,String templateName, String templatePath, Map<String, Object> root, String outFile) {
		Writer writer = null;
		System.out.println(PROJECT_PATH);
		try {
			File file = new File(templatePath + "webapp/views/" + domainObjectName.toLowerCase());
			if (!file.exists() && !file.isDirectory()) {
				file.mkdir();
			}
			File templateFile = new File(templatePath + "webapp/views/" + domainObjectName.toLowerCase()+ "/" + outFile);
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(templateFile), "UTF-8"));
			Template template = getTemplate(templatePath,templateName);
			template.process(root, writer);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
